import React, { Component } from 'react';
import { grey400 } from 'material-ui/styles/colors';
import CircularProgress from 'material-ui/CircularProgress';

import Masonry from 'react-masonry-component';
import InfiniteScroll from 'react-infinite-scroller';

import CONFIG from '../../config';
import ShowCard from '../Activity/ShowCard';
import { parseJSON, getMethod } from '../../redux/Helper';

export default class UserActivities extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      nextPageUrl: null,
      isInfiniteLoading: true
    }
  }

  componentWillMount() {
    this.initFetch();
  }

  /**
   * 初始化时加载数据
   */
  initFetch = () => {
    let request = `?token=${this.props.token}&user_id=${this.props.userData.id}`;
    let url = `${CONFIG.apiHost}/api/activity/user${request}`;
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.msg.next_page_url) {
        this.setState({isInfiniteLoading: true})
      }else{
        this.setState({isInfiniteLoading: false})
      }
      this.setState({
        data: res.msg.data,
        nextPageUrl: res.msg.next_page_url
      });
    })
  };

  /**
   * 加载时的动画
   */
  elementInfiniteLoad() {
    return (
      <div className="center-block" style={{width: 32}}>
        <CircularProgress 
          size={32} 
          style={{margin: 8}} 
          thickness={3} 
        /> 
      </div>
    );
  }

  /**
   * 滚动加载
   */
  handleInfiniteLoad = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.data;

      let request = '&token='+this.props.token;
      let url = this.state.nextPageUrl + request;

      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        setTimeout(() => {
          this.setState({
            nextPageUrl: res.msg.next_page_url,
            data: arr.concat(res.msg.data)
          });
        }, 500)
      })
    }else{
      this.setState({isInfiniteLoading: false});
    }
  };

  render() {
    let nullElement = (
      <div style={{width: '100%', textAlign: 'center'}}>
        <p style={{color: grey400}}>还没有发布活动</p>
      </div>
    );

    let elements = this.state.data.map((item, index) => {
      return (
        <ShowCard
          key={index}
          index={index}
          item={item}
          show={true}
          color500={this.props.color500}
          pushTo={this.props.pushTo}
        />  
      );
    });

  	return (
  	  <InfiniteScroll
        pageStart={0}
        loadMore={this.handleInfiniteLoad.bind(this)}
        hasMore={this.state.isInfiniteLoading}
        loader={this.elementInfiniteLoad()}
        initialLoad={false}
        useWindow={true}
        threshold={20}
      >
        <Masonry
          style={{width: '100%'}}
          elementType={'div'}
        >
          {this.state.data.length === 0 ? nullElement : elements}
        </Masonry>
      </InfiniteScroll>
  	);
  }
};
